package cn.felord.cloud.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;

import java.util.Collections;
import java.util.List;

import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR;
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.addOriginalRequestUrl;

/**
 * @author Dax
 * @since 15:16  2019-08-20
 */

public class CustomPrefixGatewayFilterFactory extends AbstractGatewayFilterFactory<CustomPrefixGatewayFilterFactory.Config> {

    private static final String CUSTOM_PREFIX = "customPrefix";

    public CustomPrefixGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            addOriginalRequestUrl(exchange, request.getURI());
            String path = request.getURI().getRawPath();

            String newPath = path.replaceFirst(config.getCustomPrefix(), "");


            ServerHttpRequest newRequest = request.mutate().path(newPath).build();

            exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, newRequest.getURI());

            return chain.filter(exchange.mutate().request(newRequest).build());
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Collections.singletonList(CUSTOM_PREFIX);
    }

    public static class Config {
        private String customPrefix;

        public String getCustomPrefix() {
            return customPrefix;
        }

        public void setCustomPrefix(String customPrefix) {
            this.customPrefix = customPrefix;
        }
    }


}
